package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.EhcacheUtil;
import com.fsd.core.util.ParametersUtil;
import com.fsd.core.wechat.entity.message.resp.TemplateMessage;
import com.fsd.core.wechat.util.WeixinUtil;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.json.JSONObject;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.E_pushtemplates;
import com.fsd.admin.model.E_userinfo;
import com.fsd.admin.model.E_wechat;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.service.E_WechatService;
import com.fsd.admin.service.E_pushtemplatesService;
import com.fsd.admin.service.E_userinfoService;
import com.fsd.admin.service.Sys_SystemParametersService;
import com.fsd.admin.dao.E_pushtemplatesDao;
import com.google.gson.Gson;

@Repository("e_pushtemplatesServiceImpl")
public class E_pushtemplatesServiceImpl extends MainServiceImpl<E_pushtemplates, String> implements E_pushtemplatesService{
    
    private static final Logger log = Logger.getLogger(E_pushtemplatesServiceImpl.class);
    private String depict = "推送模板：";
    
    @Resource(name = "e_pushtemplatesDaoImpl")
	public void setBaseDao(E_pushtemplatesDao e_pushtemplatesDao) {
		super.setBaseDao(e_pushtemplatesDao);
	}
	
	@Resource(name = "e_pushtemplatesDaoImpl")
	private E_pushtemplatesDao objectDao;
	
	@Resource(name = "Sys_SystemParametersServiceImpl")
	private Sys_SystemParametersService sysParamService;
	@Resource(name = "e_wechatServiceImpl")
	private E_WechatService wechatService;
    @Resource(name = "e_userinfoServiceImpl")
	private E_userinfoService userinfoService;
    @Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService employeeService;
	
	//消息字体颜色
	/**
     * 默认颜色-黑色
     */
	public static final String colorDefault = "#000000";

	//e_tsmbzt 推送模板状态 
	/**
     * 启用
     */
	public static final String tsmbztqy1 = "e_tsmbztqy";
	public static final String tsmbztqy2 = "启用";
	/**
     * 停用
     */
	public static final String tsmbztty1 = "e_tsmbztty";
	public static final String tsmbztty2 = "停用";
    
    //e_tsmblx 推送模板类型
	/**
     * 财务
     */
	public static final String tsmblxcw1 = "e_tsmblxcw";
	public static final String tsmblxcw2 = "财务";
	/**
     * 会员
     */
	public static final String tsmblxhy1 = "e_tsmblxhy";
	public static final String tsmblxhy2 = "会员";
	/**
     * 办公
     */
	public static final String tsmblxbg1 = "e_tsmblxbg";
	public static final String tsmblxbg2 = "办公";
	

	//============================  推送类型字典  ============================
	//推送模板Code
	//===========  财务类  ===========
	/**
     * 报销消息
     */
	public static final String pushCWbx = "cwbx";
	/**
     * 业务提示消息
     */
	public static final String pushCWywts = "cwywts";

	//===========  协同办公类  ===========
	/**
     * 待办任务消息
     */
	public static final String pushBGrwdb = "bgrwdb";
	/**
     * 任务进度消息
     */
	public static final String pushBGrwjd = "bgrwjd";
	/**
     * 任务结果消息
     */
	public static final String pushBGrwjg = "bgrwjg";

	//===========  会员类  ===========
	/**
     * 消费消息
     */
	public static final String pushHYxf = "hyxf";
	/**
     * 预约消息
     */
	public static final String pushHYyy = "hyyy";
	/**
     * 充值消息
     */
	public static final String pushHYcz = "xxtz";

	//===========  项目类  ===========

	
	//============================  业务字典  ============================
	//业务类型，页面跳转判断
	/**
     * 任务跳转处理
     */
	public static final String jumpRW = "tzrwcl";
	/**
     * 财务跳转处理
     */
	public static final String jumpCW = "tzcwcl";
	

	//============================  基本信息管理  ============================
	private static final Lock lock = new ReentrantLock();

	/**
	 * 收集整理处理消息
	 */
	private E_pushtemplates getMessageProcessObject(String wechatid, String code) throws Exception{
		lock.lock();
		Map<String, E_pushtemplates> objectMap = null;
		String strKey = Config.E_PUSHTEMPLATEMAP + wechatid;
		try {
			if(EhcacheUtil.getInstance().get(strKey) == null){
				objectMap = new HashMap<String, E_pushtemplates>();
				List<E_pushtemplates> templateList = objectDao.queryByHql(
						"from E_pushtemplates a where a.wechatid = '"+ wechatid + 
						"' and statecode = '" + tsmbztqy1 + "' order by code asc");
				for (E_pushtemplates template : templateList) {
					objectMap.put(template.getCode(), template);
				}
				EhcacheUtil.getInstance().put(strKey, objectMap);
			}else{
				objectMap = (Map<String, E_pushtemplates>)EhcacheUtil.getInstance().get(strKey);
			}
		} finally {
			lock.unlock();
		}
		if (objectMap != null && objectMap.containsKey(code))
			return objectMap.get(code);
		else
			return null;
	}
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.add(Restrictions.eq("wechatid", objectMap.get("wechatid")));
		c.addOrder(Order.asc("typecode"));
		c.addOrder(Order.asc("code"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			if(objectMap.get("typename") != null && !"".equals(objectMap.get("typename"))){
				c.add(Restrictions.like("typename", "%" + objectMap.get("typename") + "%"));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("name", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 */
	public void saveObject(E_pushtemplates obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			E_pushtemplates obj_old = objectDao.get(obj.getId());
			obj_old.setName(obj.getName());
			obj_old.setTypecode(obj.getTypecode());
			obj_old.setTypename(obj.getTypename());
			obj_old.setUrlpath(obj.getUrlpath());
			obj_old.setTemplateid(obj.getTemplateid());
			obj_old.setDetails(obj.getDetails());
			obj_old.setRemark(obj.getRemark());
			obj_old.setStatecode(tsmbztty1);
			obj_old.setStatename(tsmbztty2);
			obj_old.setUpdatedate(this.getData());//设置修改日期
			obj_old.setUpdateemployeeid(employee.getId());//设置修改用户id
			obj_old.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
			objectDao.update(obj_old);
		}else{
			//添加
			obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			obj.setStatecode(tsmbztty1);
			obj.setStatename(tsmbztty2);
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			objectDao.save(obj);
		}
		EhcacheUtil.getInstance().remove(Config.E_PUSHTEMPLATEMAP + obj.getWechatid());
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, E_pushtemplatesServiceImpl.class);
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public E_pushtemplates getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null || "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		E_pushtemplates obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
	
	/**
	 * 修改对象状态
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateEnabledObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(idList);
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		if (isEnabled){
			objectDao.executeHql("update E_pushtemplates t set t.statecode = '" + tsmbztqy1 + "', t.statename = '启用', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
			this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + " 修改“启用” " + ids, employee, E_pushtemplatesServiceImpl.class);
		}else{
			objectDao.executeHql("update E_pushtemplates t set t.statecode = '" + tsmbztty1 + "', t.statename = '停用', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
			this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + " 修改“停用” " + ids, employee, E_pushtemplatesServiceImpl.class);
		}
		E_pushtemplates obj = objectDao.get(idList.get(0));
		EhcacheUtil.getInstance().remove(Config.E_PUSHTEMPLATEMAP + obj.getWechatid());
	}
	

	

	//============================  推送管理  ============================
	/**
	 * 消息推送
	 * @param wechatApiId 微信号ApiID
	 * @param templateCode 推送模板编码
	 * @param employeeId 被推送人ID
	 * @param message 推送消息对象
	 * @throws Exception
	 */
	public void sendTemplateMessage(String wechatApiId, String templateCode, String employeeId, TemplateMessage message) throws Exception{
		A_Employee employee = this.employeeService.get(employeeId);
		this.sendTemplateMessage(wechatApiId, templateCode, employee, message, null, null, null);
	}
	
	/**
	 * 消息推送
	 * @param wechatApiId 微信号ApiID
	 * @param templateCode 推送模板编码
	 * @param employee 被推送人
	 * @param message 推送消息对象
	 * @throws Exception
	 */
	public void sendTemplateMessage(String wechatApiId, String templateCode, A_Employee employee, TemplateMessage message) throws Exception{
		this.sendTemplateMessage(wechatApiId, templateCode, employee, message, null, null, null);
	}
	
	/**
	 * 消息推送
	 * @param wechatApiId 微信号ApiID
	 * @param templateCode 推送模板编码
	 * @param employeeId 被推送人ID
	 * @param message 推送消息对象
	 * @param type业务类型
	 * @param businessId业务数据编号
	 * @param popedom操作权限
	 * @throws Exception
	 */
	public void sendTemplateMessage(String wechatApiId, String templateCode, String employeeId, TemplateMessage message, 
			String type, String businessId, String popedom) throws Exception {
		A_Employee employee = this.employeeService.get(employeeId);
		this.sendTemplateMessage(wechatApiId, templateCode, employee, message, type, businessId, popedom);
	}
	
//	/**
//	 * 消息推送
//	 * @param wechatApiId 微信号ApiID
//	 * @param templateCode 推送模板编码
//	 * @param employee 被推送人
//	 * @param message 推送消息对象
//	 * @throws Exception
//	 */
//	public void sendTemplateMessage(String wechatApiId, String templateCode, A_Employee employee, TemplateMessage message) throws Exception{
//		if(message == null) {
//			throw new BusinessException(depict + "消息对象为空，无法消息推送！");
//		}
//		if(employee == null 
//				|| !"true".equals(employee.getIswechatbind())
//				|| !"true".equals(employee.getIswechatpush())) {
//			log.error(depict + "人员微信未绑定或微信推送状态未开启！");
//			System.out.println(depict + "人员微信未绑定或微信推送状态未开启！");
//			return;
//		}
//		E_wechat wechat = null;
//		try{
//			wechat = this.wechatService.getObjectByApiId(wechatApiId);
//		}catch(Exception e){
//			log.error(depict + "微信服务器推送消息,获取微信号配置信息失败！error:{}", e);
//			System.out.println(depict + "微信服务器推送消息,获取微信号配置信息失败！" + e.getMessage());
//			return;
//		}
//		E_userinfo userinfo = this.userinfoService.getObjectByEmployeeId(employee.getId());
//		if (userinfo == null){
//			log.error(depict + "人员ID对应微信信息为空！");
//			System.out.println(depict + "人员ID对应微信信息为空！");
//			return;
//		}
//		E_pushtemplates templates = this.getMessageProcessObject(wechat.getId(), templateCode);
//		if (templates == null){
//			log.error(depict + "微信服务器推送消息,获取推送模板信息为空！");
//			System.out.println(depict + "微信服务器推送消息,获取推送模板信息为空！");
//			return;
//		}
//		if (!tsmbztqy1.equals(templates.getStatecode())){
//			log.error(depict + "推送模板不在启用状态！状态：" + templates.getStatecode());
//			System.out.println(depict + "推送模板不在启用状态！状态：" + templates.getStatecode());
//			return;
//		}
//		message.setTemplate_id(templates.getTemplateid());
//		message.setTouser(userinfo.getOpenid());
//		if (templates.getUrlpath() != null && !"".equals(templates.getUrlpath())){
//			message.setUrl(templates.getUrlpath());
//		}
//		JSONObject json = new JSONObject(message);
//		WeixinUtil.sendTemplateMessage(wechat.getAppid(), wechat.getAppsecret(), json.toString());
//	}
	
	/**
	 * 消息推送
	 * @param wechatApiId 微信号ApiID
	 * @param templateCode 推送模板编码
	 * @param employee 被推送人
	 * @param message 推送消息对象
	 * @param businessId业务数据编号
	 * @throws Exception
	 */
	public void sendTemplateMessage(String wechatApiId, String templateCode, A_Employee employee, TemplateMessage message, 
			String type, String businessId, String popedom) throws Exception {
		if(message == null) {
			throw new BusinessException(depict + "消息对象为空，无法消息推送！");
		}
		if(employee == null 
				|| !"true".equals(employee.getIswechatbind())
				|| !"true".equals(employee.getIswechatpush())) {
			log.error(depict + "人员微信未绑定或微信推送状态未开启！");
			System.out.println(depict + "人员微信未绑定或微信推送状态未开启！");
			return;
		}
		E_wechat wechat = null;
		try{
			wechat = this.wechatService.getObjectByApiId(wechatApiId);
		}catch(Exception e){
			log.error(depict + "微信服务器推送消息,获取微信号配置信息失败！error:{}", e);
			System.out.println(depict + "微信服务器推送消息,获取微信号配置信息失败！" + e.getMessage());
			return;
		}
		E_userinfo userinfo = this.userinfoService.getObjectByEmployeeId(employee.getId());
		if (userinfo == null){
			log.error(depict + "人员ID对应微信信息为空！");
			System.out.println(depict + "人员ID对应微信信息为空！");
			return;
		}
		E_pushtemplates templates = this.getMessageProcessObject(wechat.getId(), templateCode);
		if (templates == null){
			log.error(depict + "微信服务器推送消息,获取推送模板信息为空！");
			System.out.println(depict + "微信服务器推送消息,获取推送模板信息为空！");
			return;
		}
		if (!tsmbztqy1.equals(templates.getStatecode())){
			log.error(depict + "推送模板不在启用状态！状态：" + templates.getStatecode());
			System.out.println(depict + "推送模板不在启用状态！状态：" + templates.getStatecode());
			return;
		}
		message.setTemplate_id(templates.getTemplateid());
		message.setTouser(userinfo.getOpenid());
		if (type != null && !"".equals(type) && 
				templates.getUrlpath() != null && !"".equals(templates.getUrlpath())){
			message.setUrl(wechat.getAuthorizeurl() + templates.getUrlpath()+ 
					"%3ftype%3d" + type + "%26bid%3d"+ businessId +"%26popedom%3d" + popedom + "#wechat_redirect");
		}
//		:	%3a 
//		/	%2f
//		?	%3f
//		&	%26
//		=	%3d
		JSONObject json = new JSONObject(message);
		WeixinUtil.sendTemplateMessage(wechat.getAppid(), wechat.getAppsecret(), json.toString());
	}
}
